"""
FastAPI爬虫后端客户端使用示例
演示如何使用Session和浏览器管理API
"""

import requests
import json
import time
from typing import Dict, Any


class CrawlerClient:
    """爬虫API客户端"""
    
    def __init__(self, base_url: str = "http://localhost:8000"):
        self.base_url = base_url
        self.session = requests.Session()
    
    def get_health(self) -> Dict[str, Any]:
        """获取健康状态"""
        response = self.session.get(f"{self.base_url}/health")
        return response.json()
    
    # Session管理
    def get_sessions(self) -> Dict[str, Any]:
        """获取所有Session"""
        response = self.session.get(f"{self.base_url}/sessions")
        return response.json()
    
    def create_session(self, max_usage_count: int = 50, max_age_hours: int = 2) -> Dict[str, Any]:
        """创建新Session"""
        params = {
            "max_usage_count": max_usage_count,
            "max_age_hours": max_age_hours
        }
        response = self.session.post(f"{self.base_url}/sessions", params=params)
        return response.json()
    
    def get_session(self, session_id: str) -> Dict[str, Any]:
        """获取指定Session"""
        response = self.session.get(f"{self.base_url}/sessions/{session_id}")
        return response.json()
    
    def delete_session(self, session_id: str) -> Dict[str, Any]:
        """删除Session"""
        response = self.session.delete(f"{self.base_url}/sessions/{session_id}")
        return response.json()
    
    # 浏览器管理
    def get_browsers(self) -> Dict[str, Any]:
        """获取所有浏览器"""
        response = self.session.get(f"{self.base_url}/browsers")
        return response.json()
    
    def create_browser(self, name: str = None, proxy_url: str = None, headless: bool = True) -> Dict[str, Any]:
        """创建新浏览器"""
        params = {"headless": headless}
        if name:
            params["name"] = name
        if proxy_url:
            params["proxy_url"] = proxy_url
        
        response = self.session.post(f"{self.base_url}/browsers", params=params)
        return response.json()
    
    def get_browser(self, browser_id: str) -> Dict[str, Any]:
        """获取指定浏览器"""
        response = self.session.get(f"{self.base_url}/browsers/{browser_id}")
        return response.json()
    
    def close_browser(self, browser_id: str) -> Dict[str, Any]:
        """关闭浏览器"""
        response = self.session.delete(f"{self.base_url}/browsers/{browser_id}")
        return response.json()
    
    # 任务管理
    def create_task(self, 
                    url: str, 
                    session_id: str = None, 
                    browser_id: str = None,
                    handler_type: str = "default",
                    custom_data: Dict[str, Any] = None) -> Dict[str, Any]:
        """创建任务"""
        task_data = {
            "url": url,
            "handler_type": handler_type
        }
        
        if session_id:
            task_data["session_id"] = session_id
        if browser_id:
            task_data["browser_id"] = browser_id
        if custom_data:
            task_data["custom_data"] = custom_data
        
        response = self.session.post(
            f"{self.base_url}/tasks",
            json=task_data,
            headers={"Content-Type": "application/json"}
        )
        return response.json()
    
    def get_task(self, task_id: str) -> Dict[str, Any]:
        """获取任务结果"""
        response = self.session.get(f"{self.base_url}/tasks/{task_id}")
        return response.json()
    
    def get_all_tasks(self) -> Dict[str, Any]:
        """获取所有任务"""
        response = self.session.get(f"{self.base_url}/tasks")
        return response.json()
    
    def wait_for_task_completion(self, task_id: str, timeout: int = 60) -> Dict[str, Any]:
        """等待任务完成"""
        start_time = time.time()
        
        while time.time() - start_time < timeout:
            task = self.get_task(task_id)
            
            if task["status"] in ["completed", "failed"]:
                return task
            
            time.sleep(1)
        
        raise TimeoutError(f"任务 {task_id} 在 {timeout} 秒内未完成")


def demo_basic_usage():
    """基本使用演示"""
    print("🚀 FastAPI爬虫后端基本使用演示")
    print("=" * 50)
    
    client = CrawlerClient()
    
    try:
        # 1. 检查健康状态
        print("1. 检查健康状态")
        health = client.get_health()
        print(f"   健康状态: {health['status']}")
        print(f"   Sessions: {health['sessions']}")
        print(f"   Browsers: {health['browsers']}")
        print()
        
        # 2. 获取现有Sessions
        print("2. 获取现有Sessions")
        sessions = client.get_sessions()
        print(f"   现有Session数量: {len(sessions)}")
        for session in sessions:
            print(f"   - {session['id']}: 可用={session['is_usable']}, 使用次数={session['usage_count']}")
        print()
        
        # 3. 创建新Session
        print("3. 创建新Session")
        new_session = client.create_session(max_usage_count=10, max_age_hours=1)
        session_id = new_session["id"]
        print(f"   创建Session: {session_id}")
        print()
        
        # 4. 获取现有浏览器
        print("4. 获取现有浏览器")
        browsers = client.get_browsers()
        print(f"   现有浏览器数量: {len(browsers)}")
        for browser in browsers:
            print(f"   - {browser['id']}: {browser['name']}, 活跃={browser['is_active']}")
        print()
        
        # 5. 创建带代理的浏览器（如果有代理的话）
        print("5. 创建新浏览器")
        # proxy_url = "http://25052005:LuV575SE@49.7.227.22:2021"  # 取消注释以使用代理
        new_browser = client.create_browser(
            name="测试浏览器",
            # proxy_url=proxy_url,  # 取消注释以使用代理
            headless=True
        )
        browser_id = new_browser["id"]
        print(f"   创建浏览器: {browser_id}")
        print()
        
        # 6. 执行基本任务
        print("6. 执行基本任务")
        task = client.create_task(
            url="http://httpbin.org/get",
            session_id=session_id,
            browser_id=browser_id,
            handler_type="default"
        )
        task_id = task["task_id"]
        print(f"   创建任务: {task_id}")
        
        # 等待任务完成
        print("   等待任务完成...")
        completed_task = client.wait_for_task_completion(task_id)
        print(f"   任务状态: {completed_task['status']}")
        
        if completed_task["status"] == "completed":
            result = completed_task["result"]
            print(f"   页面标题: {result.get('title', 'N/A')}")
            print(f"   Session ID: {result.get('session_id', 'N/A')}")
            print(f"   Cookies数量: {result.get('cookies_count', 0)}")
        print()
        
        # 7. 执行自定义任务
        print("7. 执行自定义任务")
        custom_task = client.create_task(
            url="http://httpbin.org/html",
            session_id=session_id,
            browser_id=browser_id,
            handler_type="custom",
            custom_data={
                "selectors": {
                    "title": "title",
                    "heading": "h1"
                },
                "actions": [
                    {"type": "wait", "timeout": 1000}
                ]
            }
        )
        
        custom_task_id = custom_task["task_id"]
        print(f"   创建自定义任务: {custom_task_id}")
        
        # 等待任务完成
        print("   等待任务完成...")
        completed_custom = client.wait_for_task_completion(custom_task_id)
        print(f"   任务状态: {completed_custom['status']}")
        
        if completed_custom["status"] == "completed":
            result = completed_custom["result"]
            print(f"   提取的数据: {result.get('extracted_data', {})}")
            print(f"   执行的操作: {result.get('actions_performed', [])}")
        print()
        
        # 8. 查看最终状态
        print("8. 查看最终状态")
        final_health = client.get_health()
        print(f"   任务总数: {final_health['tasks']['total']}")
        print(f"   运行中任务: {final_health['tasks']['running']}")
        print()
        
        print("✅ 演示完成!")
        
    except Exception as e:
        print(f"❌ 错误: {e}")


def demo_login_handler():
    """登录处理器演示"""
    print("🔐 登录处理器演示")
    print("=" * 30)
    
    client = CrawlerClient()
    
    try:
        # 创建Session和浏览器
        session = client.create_session()
        browser = client.create_browser(name="登录测试浏览器")
        
        # 执行登录任务
        login_task = client.create_task(
            url="http://httpbin.org/forms/post",
            session_id=session["id"],
            browser_id=browser["id"],
            handler_type="login",
            custom_data={
                "username": "test_user",
                "password": "test_password"
            }
        )
        
        print(f"创建登录任务: {login_task['task_id']}")
        
        # 等待完成
        result = client.wait_for_task_completion(login_task["task_id"])
        print(f"登录任务结果: {result['result']}")
        
    except Exception as e:
        print(f"❌ 登录演示错误: {e}")


if __name__ == "__main__":
    print("请确保FastAPI服务器正在运行 (python app.py)")
    print("=" * 50)
    
    # 等待用户确认
    input("按回车键开始演示...")
    
    # 运行基本演示
    demo_basic_usage()
    
    print("\n" + "=" * 50)
    
    # 运行登录演示
    demo_login_handler() 